<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Eigen: The template and typename keywords in C++</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
  $(document).ready(function() { init_search(); });
/* @license-end */
</script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="eigendoxy.css" rel="stylesheet" type="text/css">
<!--  -->
<script type="text/javascript" src="eigen_navtree_hacks.js"></script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="Eigen_Silly_Professor_64x64.png"/></td>
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname"><a href="http://eigen.tuxfamily.org">Eigen</a>
   &#160;<span id="projectnumber">3.4.90 (git rev 67eeba6e720c5745abc77ae6c92ce0a44aa7b7ae)</span>
   </div>
  </td>
   <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.svg"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.svg" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('TopicTemplateKeyword.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="PageDoc"><div class="header">
  <div class="headertitle">
<div class="title">The template and typename keywords in C++ </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>There are two uses for the <code>template</code> and <code>typename</code> keywords in C++. One of them is fairly well known amongst programmers: to define templates. The other use is more obscure: to specify that an expression refers to a template function or a type. This regularly trips up programmers that use the Eigen library, often leading to error messages from the compiler that are difficult to understand, such as "expected expression" or "no match for operator&lt;".</p>
<h1><a class="anchor" id="TopicTemplateKeywordToDefineTemplates"></a>
Using the template and typename keywords to define templates</h1>
<p>The <code>template</code> and <code>typename</code> keywords are routinely used to define templates. This is not the topic of this page as we assume that the reader is aware of this (otherwise consult a C++ book). The following example should illustrate this use of the <code>template</code> keyword.</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line"><span class="keywordtype">bool</span> isPositive(T x)</div>
<div class="line">{</div>
<div class="line">    <span class="keywordflow">return</span> x &gt; 0;</div>
<div class="line">}</div>
</div><!-- fragment --><p>We could just as well have written <code>template &lt;class T&gt;</code>; the keywords <code>typename</code> and <code>class</code> have the same meaning in this context.</p>
<h1><a class="anchor" id="TopicTemplateKeywordExample"></a>
An example showing the second use of the template keyword</h1>
<p>Let us illustrate the second use of the <code>template</code> keyword with an example. Suppose we want to write a function which copies all entries in the upper triangular part of a matrix into another matrix, while keeping the lower triangular part unchanged. A straightforward implementation would be as follows:</p>
<table class="example">
<tr>
<th>Example:</th><th>Output: </th></tr>
<tr>
<td><div class="fragment"><div class="line"><span class="preprocessor">#include &lt;Eigen/Dense&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">using</span> <a class="code" href="group__matrixtypedefs.html#ga731599f782380312960376c43450eb48">Eigen::MatrixXf</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">void</span> copyUpperTriangularPart(<a class="code" href="group__matrixtypedefs.html#ga731599f782380312960376c43450eb48">MatrixXf</a>&amp; dst, <span class="keyword">const</span> <a class="code" href="group__matrixtypedefs.html#ga731599f782380312960376c43450eb48">MatrixXf</a>&amp; src)</div>
<div class="line">{</div>
<div class="line">  dst.triangularView&lt;<a class="code" href="group__enums.html#gga39e3366ff5554d731e7dc8bb642f83cdafca2ccebb604f171656deb53e8c083c1">Eigen::Upper</a>&gt;() = src.triangularView&lt;<a class="code" href="group__enums.html#gga39e3366ff5554d731e7dc8bb642f83cdafca2ccebb604f171656deb53e8c083c1">Eigen::Upper</a>&gt;();</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> main()</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="group__matrixtypedefs.html#ga731599f782380312960376c43450eb48">MatrixXf</a> m1 = <a class="code" href="classEigen_1_1DenseBase.html#a2755cb4023f7376880523626a8e05101">MatrixXf::Ones</a>(4,4);</div>
<div class="line">  <a class="code" href="group__matrixtypedefs.html#ga731599f782380312960376c43450eb48">MatrixXf</a> m2 = <a class="code" href="classEigen_1_1DenseBase.html#ae814abb451b48ed872819192dc188c19">MatrixXf::Random</a>(4,4);</div>
<div class="line">  std::cout &lt;&lt; <span class="stringliteral">&quot;m2 before copy:&quot;</span> &lt;&lt; std::endl;</div>
<div class="line">  std::cout &lt;&lt; m2 &lt;&lt; std::endl &lt;&lt; std::endl;</div>
<div class="line">  copyUpperTriangularPart(m2, m1);</div>
<div class="line">  std::cout &lt;&lt; <span class="stringliteral">&quot;m2 after copy:&quot;</span> &lt;&lt; std::endl;</div>
<div class="line">  std::cout &lt;&lt; m2 &lt;&lt; std::endl &lt;&lt; std::endl;</div>
<div class="line">}</div>
<div class="ttc" id="aclassEigen_1_1DenseBase_html_a2755cb4023f7376880523626a8e05101"><div class="ttname"><a href="classEigen_1_1DenseBase.html#a2755cb4023f7376880523626a8e05101">Eigen::DenseBase::Ones</a></div><div class="ttdeci">static const ConstantReturnType Ones()</div><div class="ttdef"><b>Definition:</b> CwiseNullaryOp.h:672</div></div>
<div class="ttc" id="aclassEigen_1_1DenseBase_html_ae814abb451b48ed872819192dc188c19"><div class="ttname"><a href="classEigen_1_1DenseBase.html#ae814abb451b48ed872819192dc188c19">Eigen::DenseBase::Random</a></div><div class="ttdeci">static const RandomReturnType Random()</div><div class="ttdef"><b>Definition:</b> Random.h:114</div></div>
<div class="ttc" id="agroup__enums_html_gga39e3366ff5554d731e7dc8bb642f83cdafca2ccebb604f171656deb53e8c083c1"><div class="ttname"><a href="group__enums.html#gga39e3366ff5554d731e7dc8bb642f83cdafca2ccebb604f171656deb53e8c083c1">Eigen::Upper</a></div><div class="ttdeci">@ Upper</div><div class="ttdef"><b>Definition:</b> Constants.h:213</div></div>
<div class="ttc" id="agroup__matrixtypedefs_html_ga731599f782380312960376c43450eb48"><div class="ttname"><a href="group__matrixtypedefs.html#ga731599f782380312960376c43450eb48">Eigen::MatrixXf</a></div><div class="ttdeci">Matrix&lt; float, Dynamic, Dynamic &gt; MatrixXf</div><div class="ttdoc">Dynamic×Dynamic matrix of type float.</div><div class="ttdef"><b>Definition:</b> Matrix.h:500</div></div>
</div><!-- fragment -->  </td><td><pre class="fragment">m2 before copy:
   0.68   0.823  -0.444   -0.27
 -0.211  -0.605   0.108  0.0268
  0.566   -0.33 -0.0452   0.904
  0.597   0.536   0.258   0.832

m2 after copy:
     1      1      1      1
-0.211      1      1      1
 0.566  -0.33      1      1
 0.597  0.536  0.258      1

</pre> </td></tr>
</table>
<p>That works fine, but it is not very flexible. First, it only works with dynamic-size matrices of single-precision floats; the function <code>copyUpperTriangularPart()</code> does not accept static-size matrices or matrices with double-precision numbers. Second, if you use an expression such as <code>mat.topLeftCorner(3,3)</code> as the parameter <code>src</code>, then this is copied into a temporary variable of type MatrixXf; this copy can be avoided.</p>
<p>As explained in <a class="el" href="TopicFunctionTakingEigenTypes.html">Writing Functions Taking Eigen Types as Parameters</a>, both issues can be resolved by making <code>copyUpperTriangularPart()</code> accept any object of type <a class="el" href="classEigen_1_1MatrixBase.html" title="Base class for all dense matrices, vectors, and expressions.">MatrixBase</a>. This leads to the following code:</p>
<table class="example">
<tr>
<th>Example:</th><th>Output: </th></tr>
<tr>
<td><div class="fragment"><div class="line"><span class="preprocessor">#include &lt;Eigen/Dense&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Derived1, <span class="keyword">typename</span> Derived2&gt;</div>
<div class="line"><span class="keywordtype">void</span> copyUpperTriangularPart(<a class="code" href="classEigen_1_1MatrixBase.html">Eigen::MatrixBase&lt;Derived1&gt;</a>&amp; dst, <span class="keyword">const</span> <a class="code" href="classEigen_1_1MatrixBase.html">Eigen::MatrixBase&lt;Derived2&gt;</a>&amp; src)</div>
<div class="line">{</div>
<div class="line">  <span class="comment">/* Note the &#39;template&#39; keywords in the following line! */</span></div>
<div class="line">  dst.template triangularView&lt;Eigen::Upper&gt;() = src.template triangularView&lt;Eigen::Upper&gt;();</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> main()</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="classEigen_1_1Matrix.html">Eigen::MatrixXi</a> m1 = <a class="code" href="classEigen_1_1DenseBase.html#a2755cb4023f7376880523626a8e05101">Eigen::MatrixXi::Ones</a>(5,5);</div>
<div class="line">  <a class="code" href="classEigen_1_1Matrix.html">Eigen::MatrixXi</a> m2 = <a class="code" href="classEigen_1_1DenseBase.html#ae814abb451b48ed872819192dc188c19">Eigen::MatrixXi::Random</a>(4,4);</div>
<div class="line">  std::cout &lt;&lt; <span class="stringliteral">&quot;m2 before copy:&quot;</span> &lt;&lt; std::endl;</div>
<div class="line">  std::cout &lt;&lt; m2 &lt;&lt; std::endl &lt;&lt; std::endl;</div>
<div class="line">  copyUpperTriangularPart(m2, m1.topLeftCorner(4,4));</div>
<div class="line">  std::cout &lt;&lt; <span class="stringliteral">&quot;m2 after copy:&quot;</span> &lt;&lt; std::endl;</div>
<div class="line">  std::cout &lt;&lt; m2 &lt;&lt; std::endl &lt;&lt; std::endl;</div>
<div class="line">}</div>
<div class="ttc" id="aclassEigen_1_1MatrixBase_html"><div class="ttname"><a href="classEigen_1_1MatrixBase.html">Eigen::MatrixBase</a></div><div class="ttdoc">Base class for all dense matrices, vectors, and expressions.</div><div class="ttdef"><b>Definition:</b> MatrixBase.h:52</div></div>
<div class="ttc" id="aclassEigen_1_1Matrix_html"><div class="ttname"><a href="classEigen_1_1Matrix.html">Eigen::Matrix</a></div><div class="ttdoc">The matrix class, also used for vectors and row-vectors.</div><div class="ttdef"><b>Definition:</b> Matrix.h:182</div></div>
</div><!-- fragment -->  </td><td><pre class="fragment">m2 before copy:
 7  9 -5 -3
-2 -6  1  0
 6 -3  0  9
 6  6  3  9

m2 after copy:
 1  1  1  1
-2  1  1  1
 6 -3  1  1
 6  6  3  1

</pre> </td></tr>
</table>
<p>The one line in the body of the function <code>copyUpperTriangularPart()</code> shows the second, more obscure use of the <code>template</code> keyword in C++. Even though it may look strange, the <code>template</code> keywords are necessary according to the standard. Without it, the compiler may reject the code with an error message like "no match
for operator&lt;".</p>
<h1><a class="anchor" id="TopicTemplateKeywordExplanation"></a>
Explanation</h1>
<p>The reason that the <code>template</code> keyword is necessary in the last example has to do with the rules for how templates are supposed to be compiled in C++. The compiler has to check the code for correct syntax at the point where the template is defined, without knowing the actual value of the template arguments (<code>Derived1</code> and <code>Derived2</code> in the example). That means that the compiler cannot know that <code>dst.triangularView</code> is a member template and that the following &lt; symbol is part of the delimiter for the template parameter. Another possibility would be that <code>dst.triangularView</code> is a member variable with the &lt; symbol referring to the <code>operator&lt;()</code> function. In fact, the compiler should choose the second possibility, according to the standard. If <code>dst.triangularView</code> is a member template (as in our case), the programmer should specify this explicitly with the <code>template</code> keyword and write <code>dst.template triangularView</code>.</p>
<p>The precise rules are rather complicated, but ignoring some subtleties we can summarize them as follows:</p><ul>
<li>A <em>dependent name</em> is name that depends (directly or indirectly) on a template parameter. In the example, <code>dst</code> is a dependent name because it is of type <code><a class="el" href="classEigen_1_1MatrixBase.html" title="Base class for all dense matrices, vectors, and expressions.">MatrixBase</a>&lt;Derived1&gt;</code> which depends on the template parameter <code>Derived1</code>.</li>
<li>If the code contains either one of the constructs <code>xxx.yyy</code> or <code>xxx-&gt;yyy</code> and <code>xxx</code> is a dependent name and <code>yyy</code> refers to a member template, then the <code>template</code> keyword must be used before <code>yyy</code>, leading to <code>xxx.template yyy</code> or <code>xxx-&gt;template yyy</code>.</li>
<li>If the code contains the construct <code>xxx::yyy</code> and <code>xxx</code> is a dependent name and <code>yyy</code> refers to a member typedef, then the <code>typename</code> keyword must be used before the whole construct, leading to <code>typename xxx::yyy</code>.</li>
</ul>
<p>As an example where the <code>typename</code> keyword is required, consider the following code in <a class="el" href="group__TutorialSparse.html">Sparse matrix manipulations</a> for iterating over the non-zero entries of a sparse matrix type:</p>
<div class="fragment"><div class="line">SparseMatrixType mat(rows,cols);</div>
<div class="line"><span class="keywordflow">for</span> (<span class="keywordtype">int</span> k=0; k&lt;mat.outerSize(); ++k)</div>
<div class="line">  <span class="keywordflow">for</span> (SparseMatrixType::InnerIterator it(mat,k); it; ++it)</div>
<div class="line">  {</div>
<div class="line">    <span class="comment">/* ... */</span></div>
<div class="line">  }</div>
</div><!-- fragment --><p>If <code>SparseMatrixType</code> depends on a template parameter, then the <code>typename</code> keyword is required:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line"><span class="keywordtype">void</span> iterateOverSparseMatrix(<span class="keyword">const</span> SparseMatrix&lt;T&gt;&amp; mat;</div>
<div class="line">{</div>
<div class="line">  <span class="keywordflow">for</span> (<span class="keywordtype">int</span> k=0; k&lt;m1.outerSize(); ++k)</div>
<div class="line">    <span class="keywordflow">for</span> (<span class="keyword">typename</span> SparseMatrix&lt;T&gt;::InnerIterator it(mat,k); it; ++it)</div>
<div class="line">    {</div>
<div class="line">      <span class="comment">/* ... */</span></div>
<div class="line">    }</div>
<div class="line">}</div>
</div><!-- fragment --><h1><a class="anchor" id="TopicTemplateKeywordResources"></a>
Resources for further reading</h1>
<p>For more information and a fuller explanation of this topic, the reader may consult the following sources:</p><ul>
<li>The book "C++ Template Metaprogramming" by David Abrahams and Aleksey Gurtovoy contains a very good explanation in Appendix B ("The typename and template Keywords") which formed the basis for this page.</li>
<li><a href="http://pages.cs.wisc.edu/~driscoll/typename.html">http://pages.cs.wisc.edu/~driscoll/typename.html</a></li>
<li><a href="http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18">http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18</a></li>
<li><a href="http://www.comeaucomputing.com/techtalk/templates/#templateprefix">http://www.comeaucomputing.com/techtalk/templates/#templateprefix</a></li>
<li><a href="http://www.comeaucomputing.com/techtalk/templates/#typename">http://www.comeaucomputing.com/techtalk/templates/#typename</a> </li>
</ul>
</div></div><!-- contents -->
</div><!-- PageDoc -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated on Thu Apr 21 2022 13:07:55 for Eigen by
    <a href="http://www.doxygen.org/index.html">
    <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.1 </li>
  </ul>
</div>
</body>
</html>
